﻿using System;
using System.Collections.Generic;
using System.Data.Objects;
using System.Linq;
using System.Text;
using CustomsNuke.Engine.CustomsException;
using CustomsNuke.Engine.Data;
using Quartz;

namespace CustomsNuke.Scheduling.Jobs
{
	public class MainJob : IJob
	{
        CustomsNukeContext _context = new CustomsNukeContext();
        public void Execute(IJobExecutionContext context)
        {
            //取已创建和已更新的Task
            try
            {
                List<Task> taskList =
                    (from task in _context.Task where task.TaskState.Id == 1 || task.TaskState.Id == 6 select task).
                        ToList();
                if (taskList != null)
                {
                    foreach (Task task in taskList)
                    {
                        JobKey getDataJobKey = new JobKey(task.Id.ToString(), task.UserId + "\\GETDATA");
                        JobKey notificationJobKey = new JobKey(task.Id.ToString(), task.UserId + "\\NOTIFICATION");
                        if (Global.Current.Scheduler.CheckExists(getDataJobKey))
                        {
                            Global.Current.Scheduler.ResumeJob(getDataJobKey);
                        }
                        else
                        {
                            //创建抓数据Job
                            IJobDetail getInfoJob = null;
                            //创建发送消息Job
                            IJobDetail notificationJob = null;
                            switch (task.BusinessId)
                            {
                                case 50:
                                    getInfoJob =
                                        JobBuilder.Create<CustomsLetPassJob>().WithIdentity(getDataJobKey).Build();
                                    notificationJob =
                                        JobBuilder.Create<NotificationLetPassJob>().WithIdentity(notificationJobKey).
                                            Build();
                                    break;
                                case 60:
                                    getInfoJob =
                                        JobBuilder.Create<CustomsContainerLadingJob>().WithIdentity(getDataJobKey).Build
                                            ();
                                    notificationJob =
                                        JobBuilder.Create<NotificationContainerLadingJob>().WithIdentity(
                                            notificationJobKey).Build();
                                    break;
                                default:
                                    break;
                            }
                            if (getInfoJob != null)
                            {
                                ITrigger trigger =
                                    TriggerBuilder.Create()
                                        .WithIdentity(task.Id.ToString(), task.UserId + "\\GETDATA")
                                        .WithSimpleSchedule(x => x.WithIntervalInMinutes(task.RunningFrequency))
                                        .StartAt(task.RunningStartTime.HasValue
                                                     ? task.RunningStartTime.Value.ToUniversalTime()
                                                     : DateTime.UtcNow)
                                        .EndAt(
                                            DateTime.UtcNow.AddMinutes(task.RunningDuration.HasValue
                                                                           ? task.RunningDuration.Value
                                                                           : 4320))
                                        .Build();
                                Global.Current.Scheduler.ScheduleJob(getInfoJob, trigger);
                            }
                            if (notificationJob != null)
                            {
                                var notifying =
                                    task.TaskNotifying.FirstOrDefault(p => p.IsDeleted == false && !p.IsDeleted);

                                if (notifying == null)
                                {
                                    return;
                                }

                                if (notifying.NotifyingPeriodically)
                                {
                                    ITrigger trigger = TriggerBuilder.Create()
                                        .WithIdentity(task.Id.ToString(), task.UserId + "\\NOTIFICATION")
                                        .WithSimpleSchedule(x => x.WithIntervalInMinutes(notifying.NotifyingFrequency))
                                        .StartAt(notifying.NotifyingStartTime.HasValue
                                                     ? notifying.NotifyingStartTime.Value.ToUniversalTime()
                                                     : DateTime.UtcNow)
                                        .EndAt(
                                            DateTime.UtcNow.AddMinutes(notifying.NotifyingDuration.HasValue
                                                                           ? notifying.NotifyingDuration.Value
                                                                           : 4320))
                                        .Build();
                                    Global.Current.Scheduler.ScheduleJob(getInfoJob, trigger);
                                }
                                if (notifying.NotifyingWhenStatusChanged)
                                {
                                    ITrigger trigger = TriggerBuilder.Create()
                                        .WithIdentity(task.Id.ToString(), task.UserId + "\\NOTIFICATION")
                                        .WithSimpleSchedule(x => x.WithIntervalInMinutes(Constant.NotificationFrequency))
                                        .StartAt(notifying.NotifyingStartTime.HasValue
                                                     ? notifying.NotifyingStartTime.Value.ToUniversalTime()
                                                     : DateTime.UtcNow)
                                        .EndAt(
                                            DateTime.UtcNow.AddMinutes(notifying.NotifyingDuration.HasValue
                                                                           ? notifying.NotifyingDuration.Value
                                                                           : 4320))
                                        .Build();
                                    Global.Current.Scheduler.ScheduleJob(notificationJob, trigger);
                                }
                            }
                        }
                        task.TaskStateId = 2;
                    }
                    _context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
                }
            }
            catch (Exception ex)
            {
                CustomsExceptionManager.HandleException(ex, ExceptionType.NothrowException);
            }
        }
	}
}
